<?php
/**
 * Created by PhpStorm.
 * User: zouyanan
 * Date: 2019/5/11
 * Time: 下午10:35
 */

namespace app\api\controller;


use app\common\controller\Api;
use app\common\library\easyWechat\MiniProgram;
use app\common\model\UserMini;
use think\Exception;

use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Validate;
use app\common\library\Token;

use app\common\controller\Weixin;

class Login extends Api
{
    protected $noNeedLogin = ['silenceLogin', 'login', 'test', 'smsCode', 'checkCode','sendSMS','register','resetpwd'];
    protected $noNeedRight = '*';

    /**
     * 微信静默登陆获取opened
     */
    public function silenceLogin(){
        $code = $this->request->post('code');//wx.login获取的code
        $nickName = $this->request->post('nickName');
        $avatarUrl = $this->request->post('avatarUrl');
        $iv = $this->request->post('iv');
        $encryptData = $this->request->post('encryptData');
        if (!$code) {
            $this->error('request must be post');
        }
        try{
            $app = MiniProgram::application();
            $authInfo = $app->sns->getSessionKey($code);
            $decodeInfo = $this->decryptData($authInfo['session_key'],  $encryptData, $iv);
            $data = [];
            if (isset($authInfo['openid'])){
                // UserMini::saveOpenid($authInfo['openid']);
                $data['openid'] = $authInfo['openid'];
            }
            if (isset($authInfo['unionid'])) {
                $data['unionid'] = $authInfo['unionid'];
            }
            if (isset($decodeInfo['unionId'])) {
                $data['unionid'] = $decodeInfo['unionid'];
            }
            if (isset($authInfo['session_key'])) {
                $data['session_key'] = $authInfo['session_key'];
            }

            if ($nickName) {
                $data['nickname'] = $nickName;
            }
            if ($avatarUrl) {
                $data['avatar'] = $avatarUrl;
            }

            $data['createtime'] = time();
            $data['updatetime'] = time();

            $info = db('user')->where('openid',$data['openid'])->find();
            if ($info) {
                $data['prevtime'] = $info['logintime'];
                $data['logintime'] = time();
                $data['loginip'] = $this->request->ip();

                $res = db('user')->where('id', $info['id'])->update($data);
                $tokenInfo = db('user_token')->find($info['id']);
                if ($tokenInfo) {
                    db('user_token')->delete($info['id']);
                }
                $this->auth->direct($info['id']);
            } else {
                $data['status'] = 'normal';
                $data['joinip'] = $this->request->ip();
                $data['loginip'] = $this->request->ip();
                $data['logintime'] = time();

                $res = db('user')->insertGetId($data);
                $this->auth->direct($res);
            }
        }catch (Exception $exception){
            $this->error($exception->getMessage());
        }
        $this->success('',['token' => $this->auth->getToken()]);
    }

    protected function decryptData( $sessionKey, $encryptedData, $iv)
    {
        if (strlen($sessionKey) != 24) {
            return falst;
        }
        $aesKey=base64_decode($sessionKey);

        if (strlen($iv) != 24) {
            return false;
        }
        $aesIV=base64_decode($iv);

        $aesCipher=base64_decode($encryptedData);

        $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj=json_decode( $result );
        if( $dataObj  == NULL )
        {
            return false;
        }
        if( $dataObj->watermark->appid != 'wxfff7fc2cc2f423fb' )
        {
            return false;
        }
        $data = json_decode( $result, true );
        return $data;
    }

    /**
     * 注册会员手机号
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     */
    public function register()
    {
        $mobile = $this->request->request('mobile');
        $password = $this->request->request('password');
        $code = $this->request->request('code');//验证码
       // $zfpass = $this->request->request('zfpass');
        $inmobile = $this->request->request('inmobile');
        //$userInfo = $this->auth->getUserinfo();
        if (!$password || !$code) {
            $this->error('缺少参数');
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error('手机号格式不正确');
        }
        //$checkCode = $this->checkCode($mobile, $code);
        //if (!$checkCode) {
           // $this->error('验证码错误');
        //}
        if(!$inmobile){
            $this->error("请填写推荐人");
        }
        //if(!$zfpass){
            //$this->error('请输入支付密码');
        //}
        $id = db('user')->field("id")->where('mobile',$inmobile)->find();
        if(!$id){
            $this->error('推荐人不存在');
        }
        $info = db('user')->where('mobile', $mobile)->find();
        if ($info) {
            $this->error('手机号已存在');
        }
        $salt = Random::alnum();
        $res = db('user')->insert([
                'mobile'   =>$mobile,
                'username' => $mobile,
                'password' => $this->auth->getEncryptPassword($password, $salt),
                'inmobile' =>$inmobile,
                'salt' => $salt,
                'createtime'=>time()
            ]
        );
        //$ret = db('user')->where('id', $userInfo['id'])->update(['mobile' => $mobile,
                                                                   // 'username' => $mobile,
                                                                  //  'salt' => $salt,
                                                                  //  'password' => $this->auth->getEncryptPassword($password, $salt) ]);
        if ($res) {
            $this->success('注册成功');
        } else {
            $this->error('注册失败');
        }
    }



    /**
     * 用户登录
     *
     * @param string $account  账号
     * @param string $password 密码
     * @param string $code 密码
     */
    public function login()
    {
        ob_clean();
        $account = $this->request->request('mobile');
        $password = $this->request->request('password');
       // $code = $this->request->request('code');
        if (!$account || !$password ) {
            $this->error('缺少参数');
        }
      //  if ($code) {
          //  $ret = 1;
          //  $checkCode = $this->checkCode($account, $code);
          //  $userInfo = db('user')->where('mobile', $account)->find();
           // if (!$userInfo) {
             //   $this->error('用户不存在');
          //  }
           // $this->auth->direct($userInfo['id']);
           // $this->success('success', ['token' => $this->auth->getToken()]);
       // } else {
            $ret = $this->auth->login($account, $password);
       // }
       // $ret = db('user')
          //  ->where('mobile',$account)
           // ->where('password',$password)
           // ->find();
        if ($ret) {
            $userinfo = $this->auth->getUserinfo();
            $data = $userinfo['token'];
            $this->success('登录成功', ['token' => $data]);
        } else {
            $this->error('登录失败');
        }
    }



    /**
     * 短信验证码
     */
    public function smsCode()
    {
        $mobile = $this->request->request('mobile');
        if (!$mobile) {
            $this->error('请填写手机号');
        }

        $info = db('telcode')->where('tel', $mobile)->find();
        if ($info && $info['expiretime'] > time()) {
            $code = $info['code'];
        } else {
            db('telcode')->where('tel', $mobile)->delete();
            $code = mt_rand(100000,999999);
        }

        $sms = new \sms\ChuanglanSmsHelper\ChuanglanSmsApi();
        $result = $sms->sendSMS($mobile,'【253云通讯】您好，您的验证码是：' . $code );
        if(!is_null(json_decode($result))){
            $output=json_decode($result,true);
            if(isset($output['code'])  && $output['code']=='0'){
                $info = db('telcode')->where('tel', $mobile)->find();
                if (!$info) {
                    $res = db('telcode')->insertGetId(['tel' => $mobile, 'code' => $code, 'expiretime' => time() + 180]);
                }
                $this->success('success');
            }else{
                $this->error($output['errorMsg']);
            }
        }else{
                $this->error($result);
        }
    }




    //短信验证码
    public function sendsms()
    {
        ob_clean();
        $mobile = $this->request->post('mobile');
        if (!$mobile) {
            $this->error('请填写手机号');
        }
        $info = db('telcode')->where('tel', $mobile)->find();
        if ($info && $info['expiretime'] > time()){
            $code = $info['code'];
        } else {
            db('telcode')->where('tel', $mobile)->delete();
            $code = mt_rand(100000,999999);
        }

        //测试
        $code = 888888;


        $mobilecheck = new \app\common\controller\Syytem;
        $data = $mobilecheck->CodePost($mobile,$code);
        switch($data){
            case 4001:
                $this->error("发送失败4001");
            case 4002:
                $this->error("发送失败4002");
            case 4003:
                $this->error("60秒内只能发送一次验证码");
            case 500:
                $this->error("发送失败");
            default:
                $info = db('telcode')->where('tel', $mobile)->find();
                if (!$info) {
                    $res = db('telcode')->insertGetId(['tel' => $mobile, 'code' => $code, 'expiretime' => time() + 180]);
                }
                $this->success("发送成功");
        }
    }




    /**
     * 核验验证码
     */
    protected function checkCode($mobile, $code)
    {

        $map['tel'] = $mobile;
        $info = db('telcode')->where($map)->find();
        if (!$info) {
            return false;
        }
        if ($code != $info['code'] || $info['expiretime'] <= time()) {
            db('telcode')->where('tel', $mobile)->delete();
            return false;
        }
        db('telcode')->where('tel', $mobile)->delete();
        db('telcode')->where('expiretime', '<=', time())->delete();
        return true;

    }


    /**
     * 重置密码
     *
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $mobile = $this->request->request("mobile");
        $newpassword = $this->request->request("newpassword");
        $captcha = $this->request->request("code");
        if (!$newpassword || !$captcha) {
            $this->error('缺少参数');
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error('手机格式不正确');
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if (!$user) {
            $this->error('用户没找到');
        }
        $ret = $this->checkCode($mobile, $captcha);
        if (!$ret) {
            $this->error('验证码不正确');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success('重置密码成功');
        } else {
            $this->error('重置密码失败');
        }
    }
}